<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use think\facade\Event;
use app\common\controller\Config;
use think\facade\Queue;

class WholesaleOrder extends Base
{

    protected $name = 'wholesale_order';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,photo,mobile,level_id,tag');
    }
    public function product()
    {
        return $this->hasOne(WholesaleProduct::class, 'id', 'product_id')->field('id,title');
    }
    public function wholesale()
    {
        return $this->hasOne(Wholesale::class, 'id', 'wholesale_id')->field('id,start_time,end_time');
    }


    public function getStatusTextAttr($value, $data)
    {
        return self::getOrderStatus($data['status']);
    }

    public function getEquityTextAttr($value, $data)
    {
        return User::getEquityStatus($data['is_equity']);
    }
    public static function getOrderStatus($value, $type = 1)
    {
        $status = [1 => '绿色权益', 2 => '红色权益', 3 => '黄色权益', 4 => '缔造中'];
        return $type == 1 ? $status[$value] : $status;
    }
    /**
     * 添加缔造
     */
    public static function  submitBuy($param, $user)
    {
        parent::startTrans();
        try {
            $find = parent::where(['uid' => $user['id']])->where('create_time', '>', time() - 10)->count();
            if (!empty($find)) {
                return ['code' => -1, 'msg' => '您操作太频繁，请稍后再试。'];
            } else {
                $info = parent::where(['uid' => $user['id']])->whereDay('create_time')->find();
                if (!empty($info)) {
                    return ['code' => -1, 'msg' => '该团项目已参与！'];
                }
                $count = WholesaleOrder::where(['wholesale_id' => $param['wid'], 'product_id' => $param['pid']])->whereDay('create_time')->count();
                $p = WholesaleProduct::where(['id' => $param['pid']])->find();
                $w = Wholesale::where(['id' => $param['wid']])->find();
                if ($count >= $p['toal']) {
                    return ['code' => -1, 'msg' => '缔造已满！'];
                }
                if ($user->assets->bonus_2 < $p['bonus_2']) {
                    return ['code' => -1, 'msg' => '缔造积分不足！'];
                }
                if ($user->assets->bonus_4 < $p['bonus_4']) {
                    return ['code' => -1, 'msg' => '燃料积分不足！'];
                }
                $is_medal = 0;
                if ($param['is_medal'] == 1) {
                    $is_medal = 1;
                    Target::Account()->basics($user->id, 'bonus_5', 1, '使用特权勋章扣除', '-')
                        ->createNormal();
                }
                $data = [
                    'uid' => $user['id'],
                    'wholesale_id' => $param['wid'],
                    'product_id' => $param['pid'],
                    'bonus_2' => $p['bonus_2'],
                    'bonus_4' => $p['bonus_4'],
                    'type' => $w['type'],
                    'end_time' => strtotime(date('Y-m-d')) + time_to_sec($w->end_time),
                    'is_medal' => $is_medal,
                    'is_equity' => $is_medal == 1 ? 1 : $user->equity,
                ];
                parent::create($data);
                Target::Account()->basics($user->id, 'bonus_4', $p['bonus_4'], '缔造燃料积分扣除', '-')
                    ->createNormal();
                Target::Account()->basics($user->id, 'bonus_2', $p['bonus_2'], '缔造缔造积分扣除', '-')
                    ->createNormal();
                parent::commit();
                $end_count = WholesaleOrder::where(['wholesale_id' => $param['wid'], 'product_id' => $param['pid']])->whereDay('create_time')->count();
                return ['code' => 1, 'msg' => '参与成功！'];
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 上午缔造结算
     */
    public static function  groupOrderSettleAm()
    {
        return self::groupOrderSettle(1);
    }

    /**
     * 下午缔造结算
     */
    public static function  groupOrderSettlePm()
    {
        return self::groupOrderSettle(2);
    }
    /**
     * 缔造到期结算
     */
    public static function  groupOrderSettle($type)
    {
        $sys = Config::lists();
        parent::startTrans();
        try {
            $info = Wholesale::where('type', $type)->find();
            $end_time = strtotime(date('Y-m-d')) + time_to_sec($info->end_time);
            $product_list = WholesaleProduct::whereIn('id', explode(',', $info->product_id))->select();
            if (count($product_list) > 0 && time() >= $end_time) {
                // if (count($product_list) > 0) {
                foreach ($product_list as $v) {
                    $data = parent::where(['type' => $type, 'product_id' => $v->id, 'status' => 4, 'is_medal' => 0, 'is_equity' => 0])->whereDay('create_time')->column('id');
                    $win_data = parent::where(['type' => $type, 'product_id' => $v->id, 'status' => 4, 'is_medal' => 1])->whereDay('create_time')->column('id');
                    $list = get_prize($data, $v->win_bl, $v->fail_bl);
                    if(!empty($win_data)){
                        parent::whereIn('id', $win_data)->update(['status' => 1, 'win_time' => time() + $sys['win_h'] * 3600]);
                    }
                    if (!empty($list['win'])) {
                        parent::whereIn('id', $list['win'])->update(['status' => 1, 'win_time' => time() + $sys['win_h'] * 3600]);
                    }
                    if (!empty($list['fail'])) {
                        parent::whereIn('id', $list['fail'])->update(['status' => 2, 'win_time' => time() + $sys['win_h'] * 3600 + 310]);
                    }
                    if (!empty($list['take'])) {
                        parent::whereIn('id', $list['take'])->update(['status' => 3, 'win_time' => time() + $sys['win_h'] * 3600 + 320]);
                    }
                    /**
                     * 标记
                     */
                    $win_id = parent::where(['type' => $type, 'product_id' => $v->id, 'status' => 4, 'is_medal' => 0, 'is_equity' => 1])->whereDay('create_time')->column('id'); //绿色标记
                    if (!empty($win_id)) {
                        parent::whereIn('id', $win_id)->update(['status' => 1, 'win_time' => time() + $sys['win_h'] * 3600]);
                    }
                    $fail_id = parent::where(['type' => $type, 'product_id' => $v->id, 'status' => 4, 'is_medal' => 0, 'is_equity' => 2])->whereDay('create_time')->column('id'); //红色标记
                    if (!empty($fail_id)) {
                        parent::whereIn('id', $fail_id)->update(['status' => 2, 'win_time' => time() + $sys['win_h'] * 3600 + 310]);
                    }
                    $take_id = parent::where(['type' => $type, 'product_id' => $v->id, 'status' => 4, 'is_medal' => 0, 'is_equity' => 3])->whereDay('create_time')->column('id');
                    if (!empty($take_id)) {
                        parent::whereIn('id', $take_id)->update(['status' => 3, 'win_time' => time() + $sys['win_h'] * 3600 + 320]);
                    }
                }
                parent::commit();
                return ['code' => 1, 'msg' => '成功！'];
            } else {
                parent::commit();
                return ['code' => -1, 'msg' => '没有数据！'];
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 绿色权益
     */
    public static function  groupOrderWin()
    {
        $sys = Config::lists();
        parent::startTrans();
        try {
            $data = parent::where(['status' => 1, 'free' => 1])->where('win_time', '<=', time())->where('win_time', '<>', 0)->select();
            // $data = parent::where(['status' => 1, 'free' => 1])->select();
            if (count($data) > 0) {
                if (count($data) > 100) {
                    //临时提高内存
                    ini_set('memory_limit', '1024M');
                }
                $jiang = 0;
                foreach ($data as $k => $v) {
                    $money = round($v['bonus_2'] * (1 + $sys['win_yield']));
                    $bonus = round($v['bonus_2'] * $sys['win_yield']);
                    Target::Account()->basics($v->uid, 'bonus_1', $money, '绿色权益收益', '+')
                        ->createNormal();
                    $res =  Relation::freeBonus($v->uid, $bonus);
                    // die;
                    /**
                     * 新增全网业绩
                     */
                    Performance::addTotal($bonus);
                    // die;
                    $jiang += $money;
                    $v->free = 2;
                    $v->free_time = time();
                    $v->save();
                }
                unset($res);
                if ($jiang > 0) {
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $jiang]);
                }
                parent::commit();
                return ['code' => 1, 'msg' => '成功！'];
            } else {
                parent::commit();
                return ['code' => -1, 'msg' => '没有数据！'];
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 红色权益
     */
    public static function  groupOrderFail()
    {
        $sys = Config::lists();
        parent::startTrans();
        try {
            $data = parent::where(['status' => 2, 'free' => 1])->where('win_time', '<=', time())->where('win_time', '<>', 0)->select();
            if (count($data) > 0) {
                if (count($data) > 100) {
                    //临时提高内存
                    ini_set('memory_limit', '1024M');
                }
                foreach ($data as $k => $v) {
                    $bonus_1 = round($v['bonus_2'] * $sys['fail_bonus_1'], 2); //绿值积分
                    $bonus_2 = round($v['bonus_2'] * $sys['fail_bonus_2'], 2); //缔造积分
                    $bonus_3 = round($v['bonus_2'] * $sys['fail_bonus_3'], 2); //FD积分
                    $bonus_5 = $sys['fail_bonus_5']; //特权勋章
                    Target::Account()->basics($v->uid, 'bonus_1', $bonus_1, '缔造红色权益返还绿值积分', '+')
                        ->createNormal();
                    Target::Account()->basics($v->uid, 'bonus_2', $bonus_2, '缔造红色权益返还缔造积分', '+')
                        ->createNormal();
                    Target::Account()->basics($v->uid, 'bonus_3', $bonus_3, '缔造红色权益返还FD积分', '+')
                        ->createNormal();
                    Target::Account()->basics($v->uid, 'bonus_5', $bonus_5, '缔造红色权益返还特权勋章', '+')
                        ->createNormal();
                    // $data = [
                    //     'uid' => $v->uid,
                    //     'bonus_k' => ['bonus_1','bonus_2','bonus_3','bonus_5'],
                    //     'bonus_data' => [$bonus_1,$bonus_2,$bonus_3,$bonus_5],
                    //     'title'=>'缔造红色权益返还'
                    // ];
                    // Queue::push('app\index\job\EquityJob', $data, 'equity');
                    $v->free = 2;
                    $v->free_time = time();
                    $v->save();
                }
                parent::commit();
                return ['code' => 1, 'msg' => '成功！'];
            } else {
                parent::commit();
                return ['code' => -1, 'msg' => '没有数据！'];
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 黄色权益
     */
    public static function  groupOrderTake()
    {
        $sys = Config::lists();
        parent::startTrans();
        try {
            $data = parent::where(['status' => 3, 'free' => 1])->where('win_time', '<=', time())->where('win_time', '<>', 0)->select();
            if (count($data) > 0) {
                if (count($data) > 100) {
                    //临时提高内存
                    ini_set('memory_limit', '1024M');
                }
                // print('<pre>');print_r($data);die;
                foreach ($data as $k => $v) {
                    $bonus_2 = round($v['bonus_2'] * $sys['take_bonus_2'], 2); //缔造积分
                    $bonus_5 = $sys['take_bonus_5']; //特权勋章
                    Target::Account()->basics($v->uid, 'bonus_2', $bonus_2, '缔造黄色权益返还缔造积分', '+')
                        ->createNormal();
                    Target::Account()->basics($v->uid, 'bonus_5', $bonus_5, '缔造黄色权益返还特权勋章', '+')
                        ->createNormal();
                    $v->free = 2;
                    $v->free_time = time();
                    $v->save();
                }
                parent::commit();
                return ['code' => 1, 'msg' => '成功！'];
            } else {
                parent::commit();
                return ['code' => -1, 'msg' => '没有数据！'];
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
